<?php

namespace Wcent\Model;

use Think\Model;

class WehatModel extends Model
{
    protected $autoCheckFields = false;

    const appid = "wxc1a669838cc93cc3";
    const secret = "5a1d431190bf39225f0151418dfdd028";
    const auth_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc1a669838cc93cc3&redirect_uri=";
    const redirect_uri = "http://analis.yyb21.com/Wcent&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    const access_token = "https://api.weixin.qq.com/sns/oauth2/access_token?";
    const uauthinfo = "https://api.weixin.qq.com/sns/userinfo?";

    public function redrict($para)
    {
        if (isset($para['code'])) {
            return true;
        } else {
            header('Location: ' . self::auth_url . self::redirect_uri);
        }
    }

    public function getAccessToken($code)
    {
        $temp = cookie('token');
        if ($temp["status"]) {
            return $temp;
        }
        $links = self::access_token . "appid=" . self::appid;
        $links.="&secret=" . self::secret . "&code=" . $code . "&grant_type=authorization_code";
        $tmp = file_get_contents($links);
        $ret = json_decode($tmp, true);
        if ($ret["access_token"] != null) {
            $return = array("status" => true, "token" => $ret["access_token"], "openid" => $ret["openid"]);
            cookie("token", $return, 7200);
            return $return;
        }
        return array("status" => false);
    }

    public function getUserInfo($token, $openid)
    {
        $links = self::uauthinfo . "access_token=" . $token . "&openid=" . $openid;
        $tmp = file_get_contents($links);
        $ret = json_decode($tmp, true);
        if ($ret['nickname'] == null) {
            return false;
        }
        return $ret;
    }
}
